package com.wq.hardcodeaudiovideostudy.soundpool;


import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;

import com.wq.hardcodeaudiovideostudy.R;

import java.util.HashMap;
/**
 * 描述     使用 SoundPool来播放音频
 * 创建     wangqi
 * 日期    2020/5/30
 */
public class SoundPoolPlayAudio {
    private static final String TAG = "SoundPoolPlayAudio";
    private static SoundPoolPlayAudio mSoundPoolPlayAudio;
    private Context mContext;
    private SoundPool soundPool;
    private HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();
    public SoundPoolPlayAudio(Context context) {
        Log.e(TAG, "SoundPoolPlayAudio()");
        this.mContext = context;
        soundPool = new SoundPool(100, AudioManager.STREAM_SYSTEM, 5);
        loadAudioResource();
    }

    public static SoundPoolPlayAudio getInstance(Context context) {
        if (mSoundPoolPlayAudio == null) {
            synchronized (SoundPoolPlayAudio.class) {
                if (mSoundPoolPlayAudio == null) {
                    mSoundPoolPlayAudio = new SoundPoolPlayAudio(context);
                }
            }
        }
        return mSoundPoolPlayAudio;
    }
    private void loadAudioResource() {
        Log.e(TAG, "  loadAudioResource()   ");
        if (soundMap.size() > 0) {
            soundMap.clear();
        }
        soundMap.put(0, soundPool.load(mContext, R.raw.start, 1));
        soundMap.put(1, soundPool.load(mContext, R.raw.stop, 1));
    }

    public void playSound(int type) {
        Log.e(TAG,
                " playSound() type = " + type + " soundMap = "
                        + soundMap.size());
        if (type == 1) {
            soundPool.play(soundMap.get(0), 1, 1, 2, 0, 1);
        } else if (type == 2) {
            soundPool.play(soundMap.get(1), 1, 1, 2, 0, 1);
        }
    }

    /**
     * 回收SoundPool资源
     */
    public void release(){
        soundPool.release();
    }
}
